package top100;

import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @author Godc
 * @description
 */
public class MergeKLists {
    public static void main(String[] args) {
        ListNode root1 = new ListNode(1);
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(5);
        root1.next = node1;
        node1.next = node2;
        ListNode root2 = new ListNode(1);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        root2.next = node3;
        node3.next = node4;
        ListNode root3 = new ListNode(2);
        ListNode node5 = new ListNode(6);
        root3.next = node5;
        MergeKListsSolution s = new MergeKListsSolution();
        ListNode[] nodes = new ListNode[]{root1,root2,root3};
        s.mergeKLists(nodes);
    }
}
class MergeKListsSolution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists==null||lists.length==0) return null;
        Queue<ListNode> queue = new PriorityQueue<>(lists.length,(v1, v2)-> v1.val-v2.val);
        for(int i = 0;i<lists.length;i++){
            queue.add(lists[i]);
        }
        ListNode dummy = new ListNode();
        ListNode p = dummy;
        while(!queue.isEmpty()){
            ListNode node = queue.poll();
            p.next = node;
            if(node.next!=null) queue.add(node.next);
            p = p.next;
        }
        return dummy.next;
    }
}
